package cn.zmit.kuxi.request;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import com.lidroid.xutils.util.LogUtils;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.request.extension.IRequest;
import com.xdroid.request.extension.config.CacheConfig;
import com.xdroid.request.extension.config.Priority;
import com.xdroid.request.extension.config.RequestMethod;
import com.xdroid.request.extension.interfaces.OnRequestListener;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import cn.zmit.kuxi.activity.BaseActivity;
import cn.zmit.kuxi.activity.MainActivity;
import cn.zmit.kuxi.contants.Url;

/**
 * * @author chenxu @parameter
 * 
 * 请求任务 * @return
 */
public class RequestTask {

	private RequestTask() {
	}

	// 单例设计模式
	private static class RequestTaskHolder {
		public static final RequestTask INSTANCE = new RequestTask();
	}

	public static RequestTask getInstance() {
		return RequestTaskHolder.INSTANCE;
	}

	/**
	 * 获取缓存请求配置
	 * 
	 * @return
	 */
	private CacheConfig getCacheRequestConfig() {

		return RequestManager.getInstance().getCacheRequestConfig();
	}

	/**
	 * 获取普通请求配置
	 * 
	 * @return
	 */

	private CacheConfig getRequestConfig() {
		return RequestManager.getInstance().getRequestConfig();
	}

	/**
	 * 获取一个请求对象
	 * 
	 * @param activity
	 * @return
	 */
	private IRequest getRequest(Activity activity) {
		IRequest request = new IRequest(activity);
		request.setTag(activity);
		request.getDefaultRequestBody().setMethod(RequestMethod.POST);
		request.setPriority(Priority.NORMAL);

		if (!StringUtils.isEmpty(CookieManager.getInstance().getCookies(
				activity))) {
			request.getDefaultRequestBody()
					.getHeaders()
					.put("Cookie",
							CookieManager.getInstance().getCookies(activity));
			LogUtils.i("设置Cookie:"
					+ CookieManager.getInstance().getCookies(activity));
		}
		return request;
	}

	/**
	 * 获取一个Context请求对象
	 * 
	 * @param activity
	 * @return
	 */
	private IRequest getRequest(Context context) {
		IRequest request = new IRequest(context);
		request.setTag(context);
		request.getDefaultRequestBody().setMethod(RequestMethod.POST);
		request.setPriority(Priority.NORMAL);

		if (!StringUtils.isEmpty(CookieManager.getInstance()
				.getCookies(context))) {
			request.getDefaultRequestBody()
					.getHeaders()
					.put("Cookie",
							CookieManager.getInstance().getCookies(context));
			LogUtils.i("设置Cookie:"
					+ CookieManager.getInstance().getCookies(context));
		}

		return request;
	}

	/**
	 * 解析请求参数
	 * 
	 * @param request
	 * @param params
	 * @return
	 */
	private IRequest parseRequestParams(IRequest request,
			Map<String, Object> params) {
		if (params == null || params.size() == 0) {
			return null;
		}
		Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> item = it.next();
			String key = item.getKey();
			Object value = item.getValue();
			if (value == null) {
				value = "";
			}
			if (value instanceof File) {
				request.getDefaultRequestBody().getFileParams()
						.put(key, (File) value);
			}
			if (value instanceof String) {
				request.getDefaultRequestBody().getParams()
						.put(key, value.toString());
			}

		}

		return request;
	}

	/**
	 * 执行请求(无参重载)
	 * 
	 * @param activity
	 * @param cacheConfig
	 * @param requestUrl
	 * @param onRequestListener
	 * @return
	 */

	private IRequest performRequest(Activity activity, CacheConfig cacheConfig,
			String requestUrl, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, cacheConfig, requestUrl, null,
				onRequestListener);
	}

	/**
	 * 执行请求(无参重载)
	 * 
	 * @param context
	 * @param cacheConfig
	 * @param requestUrl
	 * @param onRequestListener
	 * @return
	 */

	private IRequest performRequest(Context context, CacheConfig cacheConfig,
			String requestUrl, OnRequestListener<?> onRequestListener) {
		return performRequest(context, cacheConfig, requestUrl, null,
				onRequestListener);
	}

	/**
	 * 执行请求
	 * 
	 * @param activity
	 * @param cacheConfig
	 * @param requestUrl
	 * @param params
	 * @param onRequestListener
	 * @return
	 */
	private IRequest performRequest(Activity activity, CacheConfig cacheConfig,
			String requestUrl, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		IRequest request = getRequest(activity);
		request.setCacheConfig(cacheConfig);
		request.setUrl(requestUrl);
		request.setOnRequestListener(onRequestListener);
		parseRequestParams(request, params);
		RequestManager.getInstance().getRequestQueue().add(request);

		if (params != null) {
			LogUtils.i("RequestParams:" + params.toString());
		}
		return request;
	}

	private IRequest performRequest(Context context, CacheConfig cacheConfig,
			String requestUrl, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		IRequest request = getRequest(context);
		request.setCacheConfig(cacheConfig);
		request.setUrl(requestUrl);
		request.setOnRequestListener(onRequestListener);
		parseRequestParams(request, params);
		RequestManager.getInstance().getRequestQueue().add(request);

		if (params != null) {
			LogUtils.i("RequestParams:" + params.toString());
		}
		return request;
	}

	/**
	 * 注册
	 */
	public IRequest doRegist(BaseActivity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getCacheRequestConfig(), Url.REGISTER,
				params, onRequestListener);

	}

	/**
	 * 手机号码重置
	 */
	public IRequest doReSetPhone(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getCacheRequestConfig(),
				Url.RESETPHONE, params, onRequestListener);

	}

	/**
	 * 手机提交
	 */
	public IRequest doCommit(BaseActivity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getCacheRequestConfig(), Url.COMMIT,
				params, onRequestListener);

	}

	/**
	 * 获取动态码
	 */
	public IRequest doSalt(BaseActivity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(), Url.DYNAMIC,
				params, onRequestListener);

	}

	/**
	 * 立即参与提交商品
	 */
	public IRequest doCommitGoods(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(),
				Url.TOBUYCOMMITGOODS, params, onRequestListener);

	}

	/**
	 * 立即参与提交商品
	 */
	public IRequest doCartsCommitGoods(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(), Url.COMMITGOODS,
				params, onRequestListener);

	}

	/**
	 * 商品增减
	 */
	public IRequest doAdd(Context context, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		return performRequest(context, getRequestConfig(), Url.ADDGOODSNUM,
				params, onRequestListener);

	}

	/**
	 * 注册下一步提交验证码
	 */
	public IRequest doCommitSalt(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(), Url.COMMIT_DYNAMIC,
				params, onRequestListener);

	}

	/**
	 * 登陆
	 */
	public IRequest doLogin(BaseActivity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(), Url.LOGIN, params,
				onRequestListener);

	}

	/**
	 * 忘记密码
	 */
	public IRequest doForgetPwd(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(), Url.FORGET_PWD,
				params, onRequestListener);

	}

	/**
	 * 首页
	 */
	public IRequest doMain(BaseActivity activity, Map<String, Object> params,
			String page, OnRequestListener<?> onRequestListener) {
		return performRequest(activity, getRequestConfig(),
				Url.MAINDATE + page, params, onRequestListener);

	}

	/**
	 * 首页
	 */
	public IRequest getMain(BaseActivity activity,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.URL_ROOT, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;

	}

	/**
	 * 首页-顶部搜索
	 */
	public IRequest getMainSerach(Activity activity, String keyword,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.SERACH + "?keyword=" + keyword, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;

	}

	/**
	 * 最新战报
	 */
	public IRequest getNewStrecord(BaseActivity activity, String page,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.NEW_ESTRECORD + page, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;

	}

	/**
	 * 全部商品
	 */
	public IRequest getAllGoods(Activity activity, String page, String type,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.ALLGOODS + page + "?type=" + type, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;

	}

	/**
	 * 商品详情
	 */
	public IRequest getGoodsDetail(Activity activity, String gp_id,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.GOODSDETAILS + gp_id, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;

	}

	/**
	 * 立即参与
	 */
	public IRequest doGoodsBuy(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.GOODSBUY,
				params, onRequestListener);

	}

	/**
	 * 购物车列表
	 */
	public IRequest doShoppingCarts(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.SHOPPINGCARTS,
				params, onRequestListener);

	}

	/**
	 * 购物车列表
	 */
	public IRequest doShoppingCarts(Context context,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(context, getRequestConfig(), Url.SHOPPINGCARTS,
				params, onRequestListener);

	}

	/**
	 * 本期商品参与记录
	 */
	public IRequest getNowBuyRecord(BaseActivity activity, String gp_id,
			String page, OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.NOWBUYRECORD + gp_id + "?page=" + page, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 往期揭晓
	 */
	public IRequest getOldAnnounced(BaseActivity activity, String goods_id,
			String page, OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.OLDANNOUNCED + goods_id + "?page=" + page,
				onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 往期晒单
	 */
	public IRequest getOldShare(BaseActivity activity, String goods_id,
			String page, OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.OLDSHARE + goods_id + "?page=" + page, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 晒单详情
	 */
	public IRequest getShareDetails(BaseActivity activity, String evaluate_id,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.ShAREDETAILS + "?evaluate_id=" + evaluate_id,
				onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 重置密码
	 */
	public IRequest doResetPassword(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.RESETPASSWORD,
				params, onRequestListener);

	}

	/**
	 * 本期中奖者的历史参与记录
	 */
	public IRequest getHistoryRecord(BaseActivity activity, String user_id,
			String page, OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.HISTORYRECORD + user_id + "?page=" + page,
				onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 个人中心
	 */
	public IRequest doUserinfo(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.USERINFO,
				params, onRequestListener);
	}

	/**
	 * 资料修改
	 */
	public IRequest doUserinfoEdit(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.USERINFOEDIT,
				params, onRequestListener);

	}

	/**
	 * 我的参与记录——进行中
	 */
	public IRequest doJoinRecordDoing(Activity activity, String page,
			String type, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.JOINRECORDDOING
				+ page + "?type=" + type, params, onRequestListener);

	}

	/**
	 * 我的参与记录详情
	 */
	public IRequest doJoinDetails(Activity activity, String gp_id,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.JOINDETAILS
				+ gp_id, params, onRequestListener);

	}

	/**
	 * 我的参与记录——已揭晓
	 */
	public IRequest doAlreadyPublic(Activity activity, String page,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.ALREADYPUBLIC
				+ page + "?type=3", params, onRequestListener);

	}

	/**
	 * 我的参与记录——全部
	 */
	public IRequest doJoinRecordAll(Activity activity, String page,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.JOINRECORDALL
				+ page + "?type=1", params, onRequestListener);

	}

	/**
	 * 帮住中心
	 */
	public IRequest getHelpCenter(BaseActivity activity,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.HELPCENTER, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 帮住xiangqing
	 */
	public IRequest getHelpDetails(BaseActivity activity, String id,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.HELPDETAILS + id, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 我的参与记录——全部
	 */
	public IRequest doWinRecord(BaseActivity activity, String page,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.WINRECORD
				+ page, params, onRequestListener);

	}

	/**
	 * 添加单个商品到购物车
	 */
	public IRequest doAddCarts(Activity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.ADDCARTS,
				params, onRequestListener);

	}

	/**
	 * 晒单
	 */
	public IRequest doShare(Activity activity, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.SHARE, params,
				onRequestListener);

	}

	/**
	 * 删除商品
	 */
	public IRequest doDeleteGoods(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.DELETEGOODS,
				params, onRequestListener);

	}

	/**
	 * 即将揭晓详情
	 */
	public IRequest getAnnounced(BaseActivity activity, String gp_id,
			OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(activity, getRequestConfig(),
				Url.ANNOUNCE + gp_id, onRequestListener);
		request.getDefaultRequestBody().setMethod(RequestMethod.GET);
		return request;
	}

	/**
	 * 是否在购物车
	 */
	public IRequest getIsShoppingCarts(Context context,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {
		IRequest request = performRequest(context, getRequestConfig(),
				Url.ISONSHOPPING, params, onRequestListener);
		return request;
	}

	/**
	 * 充值记录
	 */
	public IRequest doRechargeRecord(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.RECHARGERECORD,
				params, onRequestListener);
	}

	/**
	 * 酷币充值
	 * 
	 * @author Joash_Yan
	 */
	public IRequest doRecharge(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.RECHARGE,
				params, onRequestListener);

	}

	/**
	 * 获得幸运号码
	 * 
	 * @author Joash_Yan
	 */
	public IRequest doGetLuckyNum(BaseActivity activity,
			Map<String, Object> params, OnRequestListener<?> onRequestListener) {

		return performRequest(activity, getRequestConfig(), Url.GETLUCKNUM,
				params, onRequestListener);

	}

	/**
	 * 版本更新
	 * 
	 * @author Joash_Yan
	 */
	public IRequest doUpdateApp(BaseActivity activity, int params,
			OnRequestListener<?> onRequestListener) {
		//
		return performRequest(activity, getRequestConfig(), Url.UPDATE
				+ "?version_code=" + params, onRequestListener);

	}

	/**
	 * 发送crash
	 */
	public IRequest doSendCrash(Context context, Map<String, Object> params,
			OnRequestListener<?> onRequestListener) {

		return performRequest(context, getRequestConfig(), Url.SENDCRASH,
				params, onRequestListener);

	}

	/**
	 * 异步加载一张图片
	 * 
	 * @param context
	 * @param url
	 * @param imageView
	 */
	public void loadImage(final Context context, final String url,
			final ImageView imageView) {
		new AsyncTask<Void, Void, Bitmap>() {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(Bitmap bitmap) {
				super.onPostExecute(bitmap);
				imageView.setImageBitmap(bitmap);
			}

			@Override
			protected Bitmap doInBackground(Void... params) {
				Bitmap bm = null;
				URLConnection con = null;
				InputStream is = null;
				try {
					URL imageURL = new URL(url);
					con = imageURL.openConnection();
					con.setDoInput(true);
					con.connect();
					is = con.getInputStream();
					// 获取资源图片
					Bitmap wholeBm = BitmapFactory.decodeStream(is, null, null);
					bm = wholeBm;

					CookieManager.getInstance().saveCookies(context,
							(HttpURLConnection) con);

					return bm;
				} catch (Exception e) {
					LogUtils.d("" + e.getMessage());
					return null;
				} finally {
					try {
						if (is != null) {
							is.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	}

}
